<?php

namespace Psg;

import('Db.Query');
import('Db.Connection');

class Teryt {

    private static function DbHandler() {
        return \Db\Connection::Open();
    }

    public static function getStates() {
        $Query = \Db\Query::Create('wojew')->Select()
                ->OrderBy(\Db\Operators::Create()->C('nazwa')->O('asc'));
        return self::DbHandler()->Query($Query);
    }

    public static function getCityOfStateId($id) {
        $Query = \Db\Query::Create('miasta')->Select()->Where(\Db\Operators::Create()
                                ->C('id_woj')->O('=')->V($id))->OrderBy(\Db\Operators::Create()
                        ->C('nazwa')->O('asc'));
        return self::DbHandler()->Query($Query);
    }

    public static function getCityName($id) {
        $Query = \Db\Query::Create('miasta')->Select(['nazwa'])
                ->Where(\Db\Operators::Create()->C('id')->O('=')->V($id));

        if (count($Q = self::DbHandler()->Query($Query)) == 0)
            $ret = "TERYT:CITYNOTEXISTS";
        else
            $ret = $Q[0]['nazwa'];

        if (substr($ret, -1) == " ")
            $ret = substr($ret, -1);

        return $ret;
    }

    public static function getStateName($id) {
        $Query = \Db\Query::Create('wojew')->Select(['nazwa'])
                ->Where(\Db\Operators::Create()->C('id')->O('=')->V($id));

        $ret = self::DbHandler()->Query($Query)[0]['nazwa'];

        if (substr($ret, -1) == " ")
            $ret = substr($ret, -1);

        return $ret;
    }

}
